import * as service from './service';

const initialQuery = {
    pageNo: 1,
    pageSize: 10,
    startDate: '',
    endDate: '',
    employeeName: '',
    companyId: 101
};

export default {
    namespace: 'workTask',

    state: {
        employeeNameList: [],
        dataSource: [],
        total: 0,
        query: initialQuery
    },

    reducers: {
        save(state, { payload }) {
            return { ...state, ...payload };
        },
        patchQuery(state, { payload }) {
            return { ...state, query: { ...state.query, ...payload } };
        },
        clearAndPatchQuery(state, { payload }) {
            return { ...state, query: { ...initialQuery, ...payload } };
        }
    },

    effects: {
        *fetch({ payload }, { call, put }) {
            const response = yield call(service.fetch, payload);
            if (response && response.code === 10000) {
                yield put({
                    type: 'save',
                    payload: {
                        dataSource: response.data.rows,
                        total: response.data.total
                    }
                });
            }
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen(location => {
                if (location.pathname !== '/stat/workStat/workOverview/work/task') {
                    return;
                }
                const { companyId = 101, pageNo = 1, pageSize = 10, reportType = 1 } = location.query;
                dispatch({
                    type: 'patchQuery',
                    payload: {
                        ...location.query,
                        companyId: +companyId,
                        pageNo: +pageNo,
                        pageSize: +pageSize,
                        reportType: +reportType
                    }
                });
            });
        }
    }
};
